package com.szosen.jkzj.activity;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.grg.idcard.IDCardManager;
import com.szosen.application.MyApplication;
import com.szosen.jkzj.R;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;

public class LoginActivity extends BaseActivity {
	private CheckBox saveCb;
	private Button loginButton;
	private EditText passwordET;
	private TextView countET;
	private Context context;

	private String passWord;
	private String count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		super.setTitleContent("【登录】");
		initView();
		// 正在运行的主桌面应用的包名
		String launcherName = MyApplication.getLauncherPackageName2(context);
		System.out.println("正在运行的主桌面应用的包名：" + launcherName);
		// Intent intent = new Intent();
		// intent.setClass(LoginActivity.this, LockScreenService.class);
		// startService(intent);
	}

	// // 这个方法用来修改之前的测量的历史记录的时间2016/10/27 为2016-10-27的格式。。。晕，之前错了
	// public void changeMeasureRecordDataTime() {
	// // 血压：
	// xueya xueya = new xueya();
	// List<Object> xueyalists = DBService.getAll(xueya);
	// for (int i = 0; i < xueyalists.size(); i++) {
	// xueya item = (xueya) xueyalists.get(i);
	// String time = item.getTime();
	// if (time.length() >= 18) {
	// item.setTime(changeStr(time));
	// }
	// DBService.update(item);
	// }
	// }
	//
	// public String changeStr(String str){
	// if(str.contains("/")){
	// return str.replace("/", "-");
	// }
	// return str;
	// }
	@Override
	@SuppressLint("ResourceAsColor")
	protected void onResume() {
		super.onResume();
		String launcherName = MyApplication.getLauncherPackageName2(context);
		if (!TextUtils.isEmpty(launcherName)) {
			// 如果勾选的主桌面没有。或者不是奥生的。就弹出选择
			if (!launcherName.contains("szosen")) {
				// clearDefaultLauncher();
				Intent paramIntent = new Intent("android.intent.action.MAIN");
				paramIntent.setComponent(new ComponentName("android",
						"com.android.internal.app.ResolverActivity"));
				paramIntent.addCategory("android.intent.category.DEFAULT");
				paramIntent.addCategory("android.intent.category.HOME");
				context.startActivity(paramIntent);
			}
		}
		if (SharedpreferenceUtil.getNeedRememberPwd(context)) {
			saveCb.setChecked(true);
			String pwd = SharedpreferenceUtil.getOffPassword(context, "123456");
			passwordET.setText(pwd);
		} else {
			saveCb.setChecked(false);
		}
		// System.out.println("resume正在运行的主桌面应用的包名：" + launcherName);
	}

	@Override
	protected void onStart() {
		super.onStart();
		final BluetoothManager bluetoothManager = (BluetoothManager) context
				.getSystemService(Context.BLUETOOTH_SERVICE);
		/*if (bluetoothManager != null) {
			BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
			if (!mBluetoothAdapter.isEnabled()) {
				mBluetoothAdapter.enable();
				TimerTask task = new TimerTask() {

					@Override
					public void run() {
						mRegisterHandler.obtainMessage(WHAT_REGISTER)
								.sendToTarget();
					}
				};
				Timer timer = new Timer();
				timer.schedule(task, 5000L);
				// 5秒后就弹出对话框。
			} else {
				checkAndShowRegisterDialog();
			}
		}*/
	}

	private final int WHAT_REGISTER = 666;
	Handler mRegisterHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == WHAT_REGISTER) {
				checkAndShowRegisterDialog();
			}
		};
	};

	private void checkAndShowRegisterDialog() {
		if (!MyApplication.isRegisterAppFromSD() && !isShowing_RegisterDialog) {
			String sn = Tools.getSerialNumber();
			String mac = Tools.getBTAddress(context);
			showRegisterDialog(sn, mac);
			isShowing_RegisterDialog = true;
		}
	}

	boolean isShowing_RegisterDialog = false;

	public void clearDefaultLauncher() {
		PackageManager pm = context.getPackageManager();
		String pn = context.getPackageName();
		String hn = LoginActivity.class.getName();
		ComponentName mhCN = new ComponentName(pn, hn);
		Intent homeIntent = new Intent("android.intent.action.MAIN");
		homeIntent.addCategory("android.intent.category.HOME");
		homeIntent.addCategory("android.intent.category.DEFAULT");
		homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		pm.setComponentEnabledSetting(mhCN, 1, 1);
		context.startActivity(homeIntent);
		pm.setComponentEnabledSetting(mhCN, 0, 1);
	}

	public void showRegisterDialog(final String sn, final String mac) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout ll = (LinearLayout) inflater.inflate(
				R.layout.dialog_register, null);
		final LinearLayout ll_sn = (LinearLayout) ll
				.findViewById(R.id.dialog_register_ll_sn);
		final LinearLayout ll_mac = (LinearLayout) ll
				.findViewById(R.id.dialog_register_ll_mac);
		final LinearLayout ll_pwd = (LinearLayout) ll
				.findViewById(R.id.dialog_register_ll_miyao);
		final TextView tv_sn = (TextView) ll_sn
				.findViewById(R.id.dialog_register_tv_sn);
		tv_sn.setText(sn);
		final TextView tv_mac = (TextView) ll_mac
				.findViewById(R.id.dialog_register_tv_mac);
		tv_mac.setText(mac);
		final EditText et_pwd = (EditText) ll_pwd
				.findViewById(R.id.dialog_register_et_pwd);
		builder.setView(ll);
		builder.setTitle("警告：");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String miyao = et_pwd.getText().toString().trim();
				boolean isRegister = MyApplication.isCheckRegisterAppOk(sn,
						mac, miyao);
				//还没注册，不能关闭窗口
				if (!isRegister) {
					ToastTool.showShort(context, "注册秘钥不正确，请重新输入！");
					// 条件不成立不能关闭 AlertDialog 窗口
					try {
						Field field = dialog.getClass().getSuperclass()
								.getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, false); // false -
													// 使之不能关闭(此为机关所在，其它语句相同)
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					boolean saveOk = Tools.saveMiYao2SD(miyao);
					if (saveOk) {
						ToastTool.showLong(context, "恭喜你，注册成功！");
					}
					// 条件成立能关闭 AlertDialog 窗口
					try {
						Field field = dialog.getClass().getSuperclass()
								.getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, true); // true - 使之可以关闭(此为机关所在，其它语句相同)
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				isShowing_RegisterDialog = false;

				// dialog.dismiss();
				// scanLeDevice(false);
			}
		});
		builder.setCancelable(false);
		// builder.setNegativeButton("取消", null);
		builder.create().show();
	}

	private void initView() {
		context = this;
		saveCb = (CheckBox) findViewById(R.id.save_password_cb);
		String userName = SharedpreferenceUtil.getOffUserName(context, "admin");
		countET = (AutoCompleteTextView) findViewById(R.id.cardNumAuto);
		countET.setText(userName);
		passwordET = (EditText) findViewById(R.id.et_passworld);
		// 如果记录是需要记住密码的。就自动默认填上密码。

		loginButton = (Button) this.findViewById(R.id.loginButton);
		OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (v == loginButton) {
					count = countET.getText().toString().trim();
					passWord = passwordET.getText().toString().trim();
					if (TextUtils.isEmpty(count) || TextUtils.isEmpty(passWord)) {
						ToastTool.showShort(context, "账号或者密码不能为空");
						return;
					}
					if (saveCb.isChecked()) {
						SharedpreferenceUtil.setNeedRememberPwd(context, true);
					} else {
						SharedpreferenceUtil.setNeedRememberPwd(context, false);
					}
					String userName = SharedpreferenceUtil.getOffUserName(
							context, "admin");
					String password = SharedpreferenceUtil.getOffPassword(
							context, "123456");
					if (count.equals(userName) && passWord.equals(password)) {
						SharedpreferenceUtil.setOffUserName(context, userName);
						SharedpreferenceUtil.setOffPassword(context, password);
						// ToastTool.showShort(context, "登录成功");
						jump2MainUi();
					} else {
						ToastTool.showShort(context, "账户密码不正确");
					}
				}
			}
		};
		loginButton.setOnClickListener(listener);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {

		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			// return true;
			// 由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
		}
		return super.onKeyDown(keyCode, event);
	}

	private void jump2MainUi() {
		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		startActivity(intent);
		// finish();
	}

}
